package redis;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.Jedis;

import java.util.function.Function;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName MyRedisClient.java
 * @Description TODO
 * @createTime 2021年04月20日 15:20:00
 */
@Slf4j
public class MyRedisClient {
    private RedisTemplate<String, Object> redisTemplate;

    public MyRedisClient(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public <T> T executeJedis(Function<Jedis, T> callback) {
        return redisTemplate.execute(conn -> {
            try {
                JedisConnection jedisConnection = (JedisConnection)conn;
                Jedis jedis = jedisConnection.getJedis();
                T result = callback.apply(jedis);
                log.debug("Jedis call result: {}", JSON.toJSONString(result));
                return result;
            } catch (Exception e) {
                log.error("executeJedis failed", e);
                return null;
            }
        }, true);
    }
}
